﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using Sunboxsoft.Common;
using Sunboxsoft.ASMS.Client.UI.Properties;
namespace Sunboxsoft.ASMS.Client.UI.Dispatching
{
    /// <summary>
    /// 派工施工
    /// </summary>
    public partial class MaintenanceBillDispatchView : UserControl, IView
    {
        #region Property
        /// <summary>
        /// 维修单号
        /// </summary>
        Guid Id;
        /// <summary>
        /// 维修单详细信息
        /// </summary>
        WebRef.MaintenanceBillDetail billDetail = null;
        Promise _promise = new Promise();
        #endregion

        #region IView 成员
        public void RegisterAction(ActionNodeCollection collection)
        {
            collection.AddAction(new ActionNode("back", Resources.isBack, "返回", btnBack_Click))
                .AddAction(new ActionNode("dispact", Resources.isDispatchingOrderList, "派工", btnDispact_Click) { IsShow = false })
                .AddAction(new ActionNode("cancelDispact", Resources.isDelete, "取消派工", btnCancelDispact_Click) { IsShow = false })
                .AddAction(new ActionNode("finish", Resources.isFinshedServiceItem, "竣工", btnFinished_Click) { IsShow = false })
                .AddAction(new ActionNode("refund", Resources.isGetMaterial, "领料退料", btnRefund_Click) { IsShow = false })
                .AddAction(new ActionNode("checked", Resources.isSettling, "订单结算", btnSettleMent_Click) { IsShow = false })
              .AddAction(new ActionNode("refresh", Resources.isRefresh, "刷新", btnRefresh_Click));
        }
        public void Active(ViewActiveArgs args)
        {
            _promise.Then(() =>
            {
                this.repositoryItemSearchLookUpEditSalesMan.BindVStaffPosition(this, _promise, Domain.Constant.StaffPosts.SalesManager);

            }).Then(BindData)
                .Run();
        }
        public void Resume(ViewResumeArgs args)
        {
            if (args.ClosedArgs.Result)
            {
                btnRefresh_Click(null, null);
            }
        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("派工施工");
        }
        #endregion

        #region Method
        public MaintenanceBillDispatchView()
        {
            InitializeComponent();
        }
        public MaintenanceBillDispatchView(Guid Id)
        {
            InitializeComponent();
            this.Id = Id;
        }
        public MaintenanceBillDispatchView(WebRef.MaintenanceBillDetail billDetail)
        {
            InitializeComponent();
            this.billDetail = billDetail;
        }
        /// <summary>
        /// 数据绑定
        /// </summary>
        private void BindData()
        {
            if (billDetail == null)
            {
                this.ShowMask("loading...");
                UIContext.Current.InvokeAsync(() =>
                {
                    SingleResult<WebRef.MaintenanceBillDetail> result = new Service.GetService().GetMaintenanceBill(Id);
                    this.BeginInvoke(new Action(() =>
                    {
                        this.HideMask();
                        if (result.IsSuccess)
                        {
                            billDetail = result.Data;
                            ShowActionByStatus();
                            BindBillDetail();
                            _promise.Resolve();
                        }
                        else
                        {
                            UIContext.Current.ViewManager.ShowError(result.Message);
                            _promise.Reject();
                        }
                    }));
                });
            }
            else
            {
                this.BeginInvoke(new Action(() =>
                {
                    Id = billDetail.Bill.Id;
                    ShowActionByStatus();
                    BindBillDetail();
                    _promise.Resolve();
                }));
            }
        }
        /// <summary>
        /// 根据维修单状态控制按钮显示
        /// </summary>
        private void ShowActionByStatus()
        {
            switch (billDetail.Bill.Status)
            {
                case Domain.Constant.MaintenanceBillStatus.WaitDispatching:
                case Domain.Constant.MaintenanceBillStatus.Working:
                    {
                        if (billDetail.Bill.ServiceItemStatus == Domain.Constant.MaintenanceBillStatus.ServiceItemStatus.Wait)
                        {
                            this.ShowAction("dispact", true);
                        }
                        else
                        {
                            this.ShowAction("dispact", false);
                        }
                        if (billDetail.Bill.ServiceItemStatus == Domain.Constant.MaintenanceBillServiceItemStatus.Working)
                        {
                            this.ShowAction("finish", true);
                            this.ShowAction("cancelDispact", true);
                        }
                        else
                        {
                            this.ShowAction("finish", false);
                            this.ShowAction("cancelDispact", false);
                        }
                        if (billDetail.Bill.MaterialCount > 0)
                        {
                            this.ShowAction("refund", true);
                        }
                        else
                        {
                            this.ShowAction("refund", false);
                        }
                        break;
                    }
                case Domain.Constant.MaintenanceBillStatus.WaitSettling:
                    this.ShowAction("dispact", false);
                    this.ShowAction("cancelDispact", false);
                    this.ShowAction("finish", false);
                    this.ShowAction("refund", false);
                    this.ShowAction("checked", true);
                    break;
            }
        }
        /// <summary>
        /// 数据初始化
        /// </summary>
        private void BindBillDetail()
        {
            this.txtCode.Text = billDetail.Bill.Number;
            this.ctltxtSalesManager.Text = billDetail.Bill.SalesManagerName;
            this.txtCreateTime.Text = billDetail.Bill.CreatedTime.ToString();
            this.txtCustomerInfo.Text = string.Format("{0}-{1}", billDetail.Bill.CustomerName, billDetail.Bill.CustomerTelephone);
            this.txtCarInfo.Text = billDetail.Bill.LPN;// string.Format("{0}-{1}-{2}", billDetail.Bill.LPN, billDetail.Bill.VIN, billDetail.Bill.EIN);
            this.txtMemo.Text = billDetail.Bill.Memo;
            for (int i = 0; i < billDetail.ServiceItemList.Length; i++)
            {
                billDetail.ServiceItemList[i].TechnicianId = billDetail.ServiceItemList[i].ActualTechnicianId != null ? billDetail.ServiceItemList[i].ActualTechnicianId : billDetail.ServiceItemList[i].TechnicianId;
            }
            this.GCServiceProject.DataSource = null;
            this.GVServiceProject.FocusedRowHandle = -1;
            this.GCServiceProject.DataSource = billDetail.ServiceItemList;
        }
        /// <summary>
        /// 创建派工单
        /// </summary>
        /// <param name="item"></param>
        private void CreateWorkingBill(WebRef.VMaintenanceBillServiceItem item)
        {
            WebRef.EWorkingBill bill = new WebRef.EWorkingBill();
            bill.MaintenanceBillId = billDetail.Bill.Id;
            bill.MaintenanceBillServiceItemId = item.Id;
            bill.ServiceItemId = item.ServiceItemId;
            if (item.TechnicianId != null)
            {
                bill.TechnicianId = new Guid(item.TechnicianId.ToString());
            }
            bill.Hour = item.Hour;
            bill.Discount = item.Discount;

            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                ServiceResult result = new Service.CreateService().CreateWorkingBill(bill);
                this.BeginInvoke(new Action(() =>
                {
                    this.HideMask();
                    if (result.IsSuccess)
                    {
                        this.btnRefresh_Click(null, null);
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
        }
        #endregion

        #region Action
        /// <summary>
        /// 返回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBack_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.CloseView(true, null);
        }
        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, object e)
        {
            billDetail = null;
            BindData();
        }
        /// <summary>
        /// 派工
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDispact_Click(object sender, object e)
        {
            try
            {
                if (this.GVServiceProject.FocusedRowHandle > -1)
                {
                    WebRef.VMaintenanceBillServiceItem item = this.GVServiceProject.GetRow(this.GVServiceProject.FocusedRowHandle) as WebRef.VMaintenanceBillServiceItem;
                    if (item.TechnicianId == null)
                    {
                        if (UIContext.Current.ViewManager.ShowQuestion("未选择技师，是否确定派工？"))
                        {
                            CreateWorkingBill(item);
                        }
                    }
                    else
                    {
                        CreateWorkingBill(item);
                    }
                }
            }
            catch (Exception ex)
            {
                UIContext.Current.ViewManager.ShowError(ex.Message);
            }
        }
        /// <summary>
        /// 取消派工
        /// </summary>
        private void btnCancelDispact_Click(object sender, object e)
        {
            if (this.GVServiceProject.FocusedRowHandle > -1)
            {
                WebRef.VMaintenanceBillServiceItem item = this.GVServiceProject.GetRow(this.GVServiceProject.FocusedRowHandle) as WebRef.VMaintenanceBillServiceItem;
                if (item.Status == Domain.Constant.MaintenanceBillServiceItemStatus.Working)
                {
                    if (UIContext.Current.ViewManager.ShowQuestion("确定要取消此笔派工？"))
                    {
                        this.ShowMask("loading...");
                        UIContext.Current.InvokeAsync(() =>
                        {
                            ServiceResult result = new Service.DeleteService().DeleteWorkingBill(billDetail.Bill.Id, item.Id);
                            this.BeginInvoke(new Action(() =>
                            {
                                if (result.IsSuccess)
                                {
                                    this.btnRefresh_Click(null, null);
                                    _promise.Resolve();
                                }
                                else
                                {
                                    UIContext.Current.ViewManager.ShowError(result.Message);
                                    _promise.Reject();
                                }
                                this.HideMask();
                            }));
                        });
                    }
                }
            }
        }
        /// <summary>
        /// 竣工
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFinished_Click(object sender, object e)
        {
            if (this.GVServiceProject.FocusedRowHandle > -1)
            {
                WebRef.VMaintenanceBillServiceItem item = this.GVServiceProject.GetRow(this.GVServiceProject.FocusedRowHandle) as WebRef.VMaintenanceBillServiceItem;
                this.ShowMask("loading...");
                UIContext.Current.InvokeAsync(() =>
                {
                    ServiceResult result = new Service.UpdateService().UpdateWorkingBillToFinished(billDetail.Bill.Id, item.Id);
                    this.BeginInvoke(new Action(() =>
                    {
                        this.HideMask();
                        if (result.IsSuccess)
                        {
                            this.btnRefresh_Click(null, null);
                            _promise.Resolve();
                        }
                        else
                        {
                            UIContext.Current.ViewManager.ShowError(result.Message);
                            _promise.Reject();
                        }
                    }));
                });
            }
        }
        /// <summary>
        /// 领料退料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefund_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.ReplaceView(new Dispatching.MaintenanceBillMaterialView(billDetail));
        }
        /// <summary>
        /// 根据服务项目状态设置数据行是否可编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GVServiceProject_ShowingEditor(object sender, CancelEventArgs e)
        {
            try
            {
                WebRef.VMaintenanceBillServiceItem entity = this.GVServiceProject.GetRow(this.GVServiceProject.FocusedRowHandle) as WebRef.VMaintenanceBillServiceItem;
                if (entity != null)
                {
                    switch (entity.ActualStatus)
                    {
                        case null:
                            e.Cancel = false;
                            break;
                        case Domain.Constant.WorkingBillStatus.Enabled:
                            e.Cancel = true;
                            break;
                        case Domain.Constant.WorkingBillStatus.Finished:
                            e.Cancel = true;
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                UIContext.Current.ViewManager.ShowError(ex.Message);
            }
        }
        /// <summary>
        /// 根据服务项目状态显示对应按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GVServiceProject_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                if (this.GVServiceProject.FocusedRowHandle > -1)
                {
                    WebRef.VMaintenanceBillServiceItem entity = GVServiceProject.GetRow(GVServiceProject.FocusedRowHandle) as WebRef.VMaintenanceBillServiceItem;
                    switch (entity.ActualStatus)
                    {
                        case null:
                            this.ShowAction("dispact", true);
                            this.ShowAction("cancelDispact", false);
                            this.ShowAction("finish", false);
                            break;
                        case Domain.Constant.WorkingBillStatus.Enabled:
                            this.ShowAction("dispact", false);
                            this.ShowAction("cancelDispact", true);
                            this.ShowAction("finish", true);
                            break;
                        case Domain.Constant.WorkingBillStatus.Finished:
                            this.ShowAction("dispact", false);
                            this.ShowAction("cancelDispact", false);
                            this.ShowAction("finish", false);
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                UIContext.Current.ViewManager.ShowError(ex.Message);
            }
        }
        /// <summary>
        /// 结算
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSettleMent_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.ReplaceView(new Dispatching.MaintenanceBillSettlementView(Id));
        }
        /// <summary>
        /// 解决选择了技师之后若焦点不离开此单元格，点击派工按钮提示“未选择技师”问题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void repositoryItemSearchLookUpEditSalesMan_EditValueChanged(object sender, EventArgs e)
        {
            if (((DevExpress.XtraEditors.SearchLookUpEdit)sender).EditValue != null)
            {
                WebRef.VMaintenanceBillServiceItem item = this.GVServiceProject.GetFocusedRow() as WebRef.VMaintenanceBillServiceItem;
                item.TechnicianId = new Guid(((DevExpress.XtraEditors.SearchLookUpEdit)sender).EditValue.ToString());
            }
        }
        #endregion
    }
}
